package cn.itcast.client;

import cn.itcast.message.*;
import cn.itcast.protocol.MessageCodecSharable;
import cn.itcast.protocol.ProcotolFrameDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
public class ChatClient {
    public static void main(String[] args) {
        NioEventLoopGroup group = new NioEventLoopGroup();
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();

        //使用CountDownLatch实现线程通信
        CountDownLatch WAIT_FOR_LOGIN = new CountDownLatch(1);
        //登陆状态标记-默认是未登陆状态
        AtomicBoolean LOGIN = new AtomicBoolean(false);

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.group(group);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ProcotolFrameDecoder());
                    ch.pipeline().addLast(MESSAGE_CODEC);
                    // 发送心跳包，让服务器知道客户端在线
                    // 建立连接之后，3s未发生WRITER_IDLE，就像服务器发送心跳包
                    // 该值为服务器端设置的READER_IDLE触发时间的一半左右
                    ch.pipeline().addLast(new IdleStateHandler(0, 3, 0));
                    ch.pipeline().addLast(new ChannelDuplexHandler() {
                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                            IdleStateEvent event = (IdleStateEvent) evt;
                            if (event.state() == IdleState.WRITER_IDLE) {
//                                log.debug("建立连接之后，客户端3秒中没有发送消息了，发送心跳包...");
                                // 发送心跳包
                                ctx.writeAndFlush(new PingMessage());
                            }
                        }
                    });
                    ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                        //读取服务器响应
                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            if (msg instanceof LoginResponseMessage) {
                                LoginResponseMessage response = (LoginResponseMessage) msg;
                                if (response.isSuccess()) {
                                    //登陆成功-设置登陆状态标记
                                    LOGIN.set(true);
                                }
                                //登陆后-唤醒登陆线程
                                WAIT_FOR_LOGIN.countDown();
                            }
                        }

                        //连接成功进行登陆操作
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            //新开辟一个线程执行登陆操作
                            new Thread(() -> {
                                //获取用户输入的用户名和密码
                                Scanner scanner = new Scanner(System.in);
                                System.out.println("请输入用户名:");
                                String username = scanner.nextLine();
                                System.out.println("请输入密码:");
                                String password = scanner.nextLine();

                                //构造登陆请求
                                LoginRequestMessage loginRequestMessage = new LoginRequestMessage(username, password);

                                //将登陆请求发送到channel中
                                ctx.writeAndFlush(loginRequestMessage);

                                //当前线程等待服务器验证用户名和密码
                                //阻塞-直到登陆成功后CountDownLatch被设置为0-即:WAIT_FOR_LOGIN.countDown();
                                try {
                                    WAIT_FOR_LOGIN.await();
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }

                                //判断登陆状态
                                if (!LOGIN.get()) {//登陆失败
                                    //关闭channel
                                    ctx.channel().close();
                                    return;
                                }

                                //登陆成功
                                while (true) {
                                    System.out.println("==================================");
                                    System.out.println("send [username] [content]");
                                    System.out.println("gsend [group name] [content]");
                                    System.out.println("gcreate [group name] [m1,m2,m3...]");
                                    System.out.println("gmembers [group name]");
                                    System.out.println("gjoin [group name]");
                                    System.out.println("gquit [group name]");
                                    System.out.println("quit");
                                    System.out.println("==================================");
                                    //获取用户输入的命令
                                    String command = scanner.nextLine();
                                    String[] messageData = command.split(" ");
                                    //匹配用户的命令
                                    switch (messageData[0]) {
                                        //单聊发送消息
                                        case "send":
                                            ChatRequestMessage chatRequestMessage = new ChatRequestMessage(username, messageData[1], messageData[2]);
                                            ctx.channel().writeAndFlush(chatRequestMessage);
                                            break;
                                        case "gsend":
                                            GroupChatRequestMessage groupChatRequestMessage = new GroupChatRequestMessage(username, messageData[1], messageData[2]);
                                            ctx.channel().writeAndFlush(groupChatRequestMessage);
                                            break;
                                        case "gcreate":
                                            String[] split = messageData[2].split(",");
                                            //小组成员-使用set集合，防止出现两个相同的成员
                                            HashSet<String> members = new HashSet<>(Arrays.asList(split));
                                            members.add(username);
                                            GroupCreateRequestMessage groupCreateRequestMessage = new GroupCreateRequestMessage(messageData[1], members);
                                            ctx.writeAndFlush(groupCreateRequestMessage);
                                            break;
                                        case "gmembers":
                                            GroupMembersRequestMessage groupMembersRequestMessage = new GroupMembersRequestMessage(messageData[1]);
                                            ctx.writeAndFlush(groupMembersRequestMessage);
                                            break;
                                        case "gjoin":
                                            GroupJoinRequestMessage groupJoinRequestMessage = new GroupJoinRequestMessage(username, messageData[1]);
                                            ctx.writeAndFlush(groupJoinRequestMessage);
                                            break;
                                        case "gquit":
                                            GroupQuitRequestMessage groupQuitRequestMessage = new GroupQuitRequestMessage(username, messageData[1]);
                                            ctx.writeAndFlush(groupQuitRequestMessage);
                                            break;
                                        case "quit":
                                            ctx.channel().close();
                                            return;
                                    }
                                }

                            }, "LoginThread").start();
                        }
                    });
                }
            });
            Channel channel = bootstrap.connect("localhost", 8080).sync().channel();
            channel.closeFuture().sync();
        } catch (Exception e) {
            log.error("client error", e);
        } finally {
            group.shutdownGracefully();
        }
    }
}
